import { request } from '@/utils/request'

const state = {
  recentRecords: [],
  calorieTrendData: {
    labels: [],
    datasets: [{
      label: '摄入',
      data: [],
      borderColor: '#36A2EB',
      backgroundColor: 'rgba(54, 162, 235, 0.2)',
      tension: 0.3
    }, {
      label: '消耗',
      data: [],
      borderColor: '#FF6384',
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      tension: 0.3
    }]
  },
  nutritionDistributionData: {
    labels: ['蛋白质', '碳水化合物', '脂肪'],
    datasets: [{
      data: [0, 0, 0],
      backgroundColor: [
        '#4BC0C0',
        '#FFCE56',
        '#FF6384'
      ],
      hoverBackgroundColor: [
        '#5AD3D1',
        '#FFDA79',
        '#FF7A96'
      ]
    }]
  }
}

const mutations = {
  SET_RECENT_RECORDS(state, records) {
    state.recentRecords = records
  },
  SET_CALORIE_TREND_DATA(state, data) {
    state.calorieTrendData = data
  },
  SET_NUTRITION_DISTRIBUTION_DATA(state, data) {
    state.nutritionDistributionData.datasets[0].data = data
  }
}

const actions = {
  async fetchCalorieData({ commit }) {
    try {
      // 获取最近记录
      const recordsResponse = await request({
        url: '/api/calorie/records',
        method: 'get'
      })
      commit('SET_RECENT_RECORDS', recordsResponse.data)

      // 获取卡路里趋势
      const trendResponse = await request({
        url: '/api/calorie/trend',
        method: 'get'
      })
      commit('SET_CALORIE_TREND_DATA', trendResponse.data)

      // 获取营养分布
      const nutritionResponse = await request({
        url: '/api/calorie/nutrition',
        method: 'get'
      })
      commit('SET_NUTRITION_DISTRIBUTION_DATA', nutritionResponse.data)
    } catch (error) {
      console.error('获取卡路里数据失败', error)
      throw error
    }
  },
  async addCalorieRecord({ dispatch }, record) {
    try {
      await request({
        url: '/api/calorie/record',
        method: 'post',
        data: record
      })
      await dispatch('fetchCalorieData')
    } catch (error) {
      console.error('添加卡路里记录失败', error)
      throw error
    }
  },
  async deleteCalorieRecord({ dispatch }, id) {
    try {
      await request({
        url: `/api/calorie/record/${id}`,
        method: 'delete'
      })
      await dispatch('fetchCalorieData')
    } catch (error) {
      console.error('删除卡路里记录失败', error)
      throw error
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}    